package com.fh.fruit.controller.goods;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.fruit.entity.goods.Goods;
import com.fh.fruit.entity.goods.GoodsUnit;
import com.fh.fruit.entity.label.Label;
import com.fh.fruit.entity.label.LabelAttr;
import com.fh.fruit.entity.spec.Spec;
import com.fh.fruit.service.classify.ClassifyManager;
import com.fh.fruit.service.goods.GoodsManager;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.Jurisdiction;
import com.fh.util.PageData;
import com.fh.util.Tools;

@Controller
@RequestMapping(value = "/goods")
public class GoodsController extends BaseController {
	String menuUrl = "goods/listAllClassify.do"; // 商品地址(权限用)

	@Resource(name = "goodsService")
	private GoodsManager goodsService;
	
	@Resource(name = "classifyService")
	private ClassifyManager classifyService;
	
	
	/**显示商品列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	public ModelAndView listGoods(Page page,HttpSession httpSession)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String keywords = pd.getString("keywords");				//关键词检索条件
		if(StringUtils.isNotEmpty(keywords)){
			pd.put("keywords", keywords.trim());
		}
		String id=pd.getString("id");
		String classIds="";
		if(Tools.notEmpty(id)){
			classIds = (String) goodsService.getClassIdByPid(id);
		}else{
			classIds=pd.getString("classIds");
		}
		pd.put("classIds", classIds);
		page.setPd(pd);
		page.setShowCount(5);
		List<Goods>	goodsList = goodsService.listGoods(page);
		
		mv.setViewName("farm/goods/goods_list");
		mv.addObject("goodsList", goodsList);
		mv.addObject("pd", pd);
		mv.addObject("classIds",classIds);
		mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
		return mv;
	}
	
	/**
	 * 显示分类列表ztree(分类管理)
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listAllClassify")
	public ModelAndView listAllClassify(Model model, String id) throws Exception {
		ModelAndView mv = this.getModelAndView();
		try {
			mv.setViewName("farm/goods/classify_ztree");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	
	@RequestMapping("/asynTree")
	public void asynTree(HttpServletRequest request, HttpServletResponse response){
		PrintWriter out =null;
		response.setCharacterEncoding("UTF-8"); 
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String id = request.getParameter("id");
        String name = request.getParameter("name");  
        String level = request.getParameter("level");  
        String otherParam = request.getParameter("otherParam");
        String orgin =request.getParameter("orgin");
        System.out.println(id + "|" + name + "|" + level + "|" + otherParam); 
        List<PageData> list = null;
        List<PageData> lists = new ArrayList<>();
		try {
			list = classifyService.synTree(Integer.parseInt(id));
			for (int i = 0; i < list.size(); i++) {
				@SuppressWarnings("unchecked")
				HashMap<String, Object>  maps= list.get(i); 
				PageData pd = new PageData();
				pd.put("id", maps.get("id"));
				pd.put("name", maps.get("name"));
				pd.put("pId", maps.get("pId"));
				pd.put("isParent", true);
				pd.put("open", false);
				if ("classify".equals(orgin)) {
					pd.put("url", "classify.do?id="+maps.get("id"));
				}else{
					pd.put("url", "goods/list.do?id="+maps.get("id"));
				}
				
				pd.put("target", "treeFrame");
				lists.add(i, pd);
			}
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
			out.write(JSON.toJSONString(lists));
	}
	
	/**
	 * 去新增商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goAddG")
	public ModelAndView goAddG(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String state=pd.getString("state");
		List<GoodsUnit> unit=goodsService.getGoodsUnitList();
		mv.setViewName("farm/goods/goods_edit");
		mv.addObject("msg", "saveG");
		mv.addObject("unit", unit);
		mv.addObject("state", state);
		return mv;
	}
	
	/**
	 * 新增商品
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveG")
	public ModelAndView saveU(HttpServletRequest requset) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "新增商品");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("createId", user.getUSER_ID()); // 创建人
		pd.put("createTime", DateUtil.getTime()); // 创建时间
		int num=goodsService.saveG(pd);
		if(num ==2){
			mv.addObject("msg", "商品已存在,保存失败!");
		}
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 去修改商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEditG")
	public ModelAndView goEditG(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String state=pd.getString("state");
		Goods goods = goodsService.findById(pd);
		List<GoodsUnit> unit=goodsService.getGoodsUnitList();
		mv.setViewName("farm/goods/goods_edit");
		mv.addObject("pd", pd);
		mv.addObject("msg", "editG");
		mv.addObject("goods", goods);
		mv.addObject("unit", unit);
		mv.addObject("state", state);
		return mv;
	}
	
	/**
	 * 保存商品
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editG")
	public ModelAndView editG(Goods goods,HttpServletRequest requset) throws Exception {

		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "修改商品");
		ModelAndView mv = this.getModelAndView();
		PageData pd = null;
		try {
			pd = this.getPageData();
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("updateId", user.getUSER_ID()); // 修改人
			pd.put("updateTime", DateUtil.getTime()); // 修改时间
			goodsService.editG(pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			mv.addObject("msg", "failed");
		}
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 删除商品
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delGood")
	@ResponseBody
	public String delGood(HttpServletRequest requset) {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "删除商品");
		PageData pd = this.getPageData();
		try {
			goodsService.delGood(pd);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
	}
	
	/**
	 * 批量删除商品
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delGoods")
	@ResponseBody
	public String delGoods(HttpServletRequest requset) {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "删除商品");
		PageData pd = this.getPageData();
		try {
			goodsService.delGoods(pd);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
	}
	
	/**
	 * 修改上下架状态
	 */
	@RequestMapping(value = "updateState")
	@ResponseBody
	public String updateState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date();
		String endTime= pd.getString("endTime");
		Date et= sdf.parse(endTime);
		Date nt=sdf.parse(sdf.format(date));
		 if (et.getTime() <= nt.getTime()) {
			 return "timeEnd";
		 }
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("updateId", user.getUSER_ID()); // 修改人
		pd.put("updateTime", DateUtil.getTime()); // 修改时间
		int num=goodsService.updateState(pd);
		return num==1?"success":"failed";
	}
	
	/**
	 * 去添加规格页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toGoodsSpec")
	public ModelAndView toGoodsSpec(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("farm/goods/goods_spec");
		return mv;
	}
	
	/**
	 * 去规格列表页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goodsSpecList")
	public ModelAndView  goodsSpecList(Page page) throws Exception{
		ModelAndView view = this.getModelAndView();
		PageData pd = this.getPageData();
		page.setPd(pd);
		List<Spec> spec=goodsService.getGoodsSpecList(page);
		if(spec != null){
			for (int i =0;i<spec.size();i++) {
				if(spec.get(i).getSpec()!=null){
					String[] sp=spec.get(i).getSpec().split("-");
					for (int y = 0; y < sp.length; y++) {
						LabelAttr label=goodsService.getLabelAttr(sp[y]);
						spec.get(i).getLabelAttr().add(label);
					}
				}
				/*String endTime= spec.get(i).getEndTime();
				Date et= sdf.parse(endTime);
				Date nt=sdf.parse(sdf.format(date));
				 if (et.getTime() <= nt.getTime()) {
					 goodsService.updateSpecStates(spec.get(i)); 
		         }*/
			}
		}
		List<Label> label=goodsService.getGoodsLabelList(pd);
		view.addObject("spec", spec);
		view.addObject("pd",pd);
		view.addObject("label",label);
		view.setViewName("farm/goods/goods_spec_list");
		view.addObject("QX",Jurisdiction.getHC());	//按钮权限
		logBefore(logger, view.toString());
		return view;
	} 
	
	/**
	 * 去规格修改页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "toSpecEdit")
	public ModelAndView  toSpecEdit(Page page) throws Exception{
		ModelAndView view = this.getModelAndView();
		PageData pd = this.getPageData();
		Spec spec = goodsService.getGoodsSpec(pd);
		List<LabelAttr> la= new ArrayList<LabelAttr>();
		if(spec.getSpec()!=null){
			String[] sp=spec.getSpec().split("-");
			for (int i = 0; i < sp.length; i++) {
				LabelAttr label=goodsService.getLabelAttr(sp[i]);
				la.add(label);
			}
		}
		view.addObject("spec", spec);
		view.addObject("la", la);
		view.addObject("pd", pd);
		view.setViewName("farm/goods/goods_spec_edit");
		view.addObject("QX",Jurisdiction.getHC());	//按钮权限
		logBefore(logger, view.toString());
		return view;
	}
	
	/**
	 * 规格修改
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "specEdit")
	public ModelAndView specEdit(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("updateId", user.getUSER_ID()); // 修改人
			pd.put("updateTime", DateUtil.getTime()); // 修改时间
			goodsService.updateGoodsEdit(pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			mv.addObject("msg", "failed");
		}
		mv.setViewName("save_result");
		return mv;
	}
	
	
	/**
	 * 修改规格上下架状态
	 */
	@RequestMapping(value = "updateSpecState")
	@ResponseBody
	public String updateSpecState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date();
		String endTime= pd.getString("endTime");
		Date et= sdf.parse(endTime);
		Date nt=sdf.parse(sdf.format(date));
		 if (et.getTime() <= nt.getTime()) {
			 return "timeEnd";
		 }
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("updateId", user.getUSER_ID()); // 修改人
		pd.put("updateTime", DateUtil.getTime()); // 修改时间
		int num=goodsService.updateSpecState(pd);
		return num==1?"success":"failed";
	}
	
	/**
	 * 批量上下架商品
	 * 
	 */
	@RequestMapping(value = "updateBatchState")
	@ResponseBody
	public String updateBatchState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		PageData pd = this.getPageData();
		String stat = pd.getString("state");
		String ids = pd.getString("ids");
		String[] str = ids.split(",");
		for (String st : str) {
			PageData p =new PageData();
			p.put("id", st);
			p.put("state", stat);
			p.put("updateId", user.getUSER_ID());
			p.put("updateTime", DateUtil.getTime());
			Goods goods = goodsService.findById(p);
			String endTime= goods.getEndTime();
			Date et= sdf.parse(endTime);
			Date nt=sdf.parse(sdf.format(date));
			 if (et.getTime() <= nt.getTime()) {
				 return "timeEnd"+st;
			 }
			int num=goodsService.updateBatchState(p);
			if(num ==0){
				return "failed";
			}
		}
		return "success";
	}
	
	/**
	 * 批量上下架规格
	 * 
	 */
	@RequestMapping(value = "updateSpecStateList")
	@ResponseBody
	public String updateSpecStateList(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		PageData pd = this.getPageData();
		String stat = pd.getString("state");
		String ids = pd.getString("ids");
		String[] str = ids.split(",");
		for (String st : str) {
			PageData p =new PageData();
			p.put("specId", st);
			p.put("state", stat);
			p.put("updateId", user.getUSER_ID());
			p.put("updateTime", DateUtil.getTime());
			Spec spec = goodsService.getGoodsSpec(p);
			String endTime= spec.getEndTime();
			Date et= sdf.parse(endTime);
			Date nt=sdf.parse(sdf.format(date));
			 if (et.getTime() <= nt.getTime()) {
				 return "timeEnd"+st;
			 }
			int num=goodsService.updateSpecStateList(p);
			if(num ==0){
				return "failed";
			}
		}
		return "success";
	}
	
}
